#include <qqtlongdataserialization.h>


QQtLongDataSerialization::QQtLongDataSerialization ( QObject* parent )
    : QQtDataSerialization ( parent ) {}

QQtLongDataSerialization::~QQtLongDataSerialization() {}

int QQtLongDataSerialization::length() const
{
    return 4 + 4 + dictionary().toJson ( QJsonDocument::Compact ).size() + 4 + 4;
}

void QQtLongDataSerialization::dump() const
{
    quint32 header = 0x77EE;
    quint32 size = 0;
    QByteArray json_data;
    quint32 checksum = 0;
    quint32 tail = 0x77FF;

    QByteArray bytes = buffer();
    bytes >> header >> size;
    int json_size = size - ( 4 + 4 + 4 + 4 );
    json_data.resize ( json_size );
    bytes >> json_data;
    bytes >> checksum >> tail;

    qDebug() << "{" << hex << header << ", "
             << oct << size  << ", "
             << oct << json_data.size() << ", "
             << hex << checksum << ", "
             << hex << tail
             << "}";

    QQtDictionary dict;
    dict.fromJson ( json_data );
    QByteArray data = dict.toJson ( QJsonDocument::Indented );
    qDebug() << qPrintable ( data );
}

void QQtLongDataSerialization::packer ( QByteArray& l ) const
{
    quint32 header = 0x77EE;
    quint32 size = 0;
    QByteArray json_data;
    quint32 checksum = 0;
    quint32 tail = 0x77FF;

    json_data = dictionary().toJson ( QJsonDocument::Compact );
    size = 4 + 4 + json_data.size() + 4 + 4;
    for ( int i = 0; i < json_data.size(); i++ )
    {
        char check = json_data.data() [i];
        if ( checksum + check >= 0x77FF )
            checksum = 0;
        checksum = checksum + ( quint32 ) check;
    }
    QByteArray& bytes = l;
    bytes << header << size << json_data << checksum << tail;
}

void QQtLongDataSerialization::parser ( const QByteArray& _l )
{
    quint32 header = 0x77EE;
    quint32 size = 0;
    QByteArray json_data;
    quint32 checksum = 0;
    quint32 tail = 0x77FF;

    QByteArray bytes = _l;
    bytes >> header >> size;
    int json_size = size - ( 4 + 4 + 4 + 4 );
    json_data.resize ( json_size );
    bytes >> json_data;
    bytes >> checksum >> tail;

    QQtDictionary& dict = dictionary();
    dict.fromJson ( json_data );
}
